package www.sofn.com.utils;


import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpSession;
import www.sofn.com.domain.R;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class ServletUtils {

    private ServletUtils() {

    }

    /**
     * 返回json
     *
     * @param r
     */
    public static void responseWriterJson(R r, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        try {
            writer.write(JSONUtil.toJsonStr(r));
        } catch (Exception e) {
            log.error("[Response转Json失败]，{}", e);
        } finally {
            writer.close();
            response.flushBuffer();
        }
    }

    /**
     * 获取request
     */

    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }
    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
}
